package cn.edu.nwafu.mail.controller;

import cn.edu.nwafu.common.exception.Assert;
import cn.edu.nwafu.common.result.R;
import cn.edu.nwafu.common.result.ResponseEnum;
import cn.edu.nwafu.common.util.RandomUtils;
import cn.edu.nwafu.mail.service.SendEmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "发送邮件")
@RestController
@RequestMapping("/api/mail")
@Slf4j
public class SendMailController {
    @Autowired
    private SendEmailService sendEmailService;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("发送邮件验证码")
    @GetMapping("/send/{mail}")
    public R send(
            @ApiParam(value = "收件方邮箱", required = true)
            @PathVariable String mail
    ) {
        Assert.isTrue(!"undefined".equals(mail), ResponseEnum.SEND_MAIL_EMPTY_ERROR);
        // 验证邮箱不能为空
        Assert.notEmpty(mail, ResponseEnum.SEND_MAIL_EMPTY_ERROR);
        // 验证邮箱格式是否正确
//        Assert.isTrue(RegexValidateUtils.checkEmail(mail), ResponseEnum.MAIL_ERROR);


        // 判断手机是否已经注册
//        boolean result = userInfoClient.checkMobile(mail);
//        Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);


        String code = RandomUtils.getSixBitRandom();
        sendEmailService.sendEmail(code,mail);

        // 将验证码存入redis
        redisTemplate.opsForValue().set("airline:registration:code:" + mail, code, 5, TimeUnit.MINUTES);

        return R.ok().message("发送邮件验证码成功").data("code", code);
    }
}
